import router from '@/router'
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
import { useStorage } from '@vueuse/core'
import {useUserStore} from '@/stores/modules/user'
import {useMenuStore} from '@/stores/modules/menu'
//白名单
const whiteList = ['/login', '/register']

router.beforeEach(async(to,from,next)=>{
	const userStore = useUserStore()
	const menuStore = useMenuStore()
		//访问某一个路由之前的守卫
		nprogress.start()
		document.title = to.meta.title
		const hasToken = useStorage('TOKEN')
		if(hasToken.value != 'undefined'){
			if(to.path == '/login'){
				 next({ path: '/' })
				 nprogress.done()
			}else{
				// 如果有token 判断用户有没有权限信息
				 const hasRoles = userStore.user.roles && userStore.user.roles.length >0
				 if(hasRoles){
					 	 next()
				 }else{
					 await userStore.getInfo()
					 await menuStore.getUserMenuList(userStore.user.accountId)
					 .then((resp)=>{
							const asyncRoutes = resp
							asyncRoutes.forEach((route)=>{
								// 添加路由
								router.addRoute(route)
							})
								next({...to,replace: true})
					 }).catch((error)=>{
					 })
				 }
			}
		}else{
			if (whiteList.indexOf(to.path) !== -1) {
			      // in the free login whitelist, go directly
			      next()
			    } else {
						next(`/login?redirect=${to.fullPath}`)
						nprogress.done()
			}
		}
			
})

//全局后置守卫
router.afterEach((to, from) => {
  // to and from are both route objects.
  nprogress.done()
})
